<script setup>
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { fetchCourses } from "../api/demo";

const router = useRouter();

const loading = ref(true);
const refreshing = ref(false);
const courses = ref([]);

const currentPage = ref(1);
const pageSize = ref(8);

const apiBase = (import.meta.env.VITE_API_BASE || "http://10.1.6.130").replace(/\/?$/, "");

const FALLBACK_COVER = (() => {
  const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='720' height='420'>
      <defs>
        <linearGradient id='g' x1='0%' y1='0%' x2='100%' y2='100%'>
          <stop offset='0%' stop-color='#e0f2ff'/>
          <stop offset='100%' stop-color='#9ab8ff'/>
        </linearGradient>
      </defs>
      <rect width='720' height='420' fill='url(#g)' />
      <text x='50%' y='50%' dominant-baseline='middle' text-anchor='middle'
        font-family='PingFang SC, Microsoft YaHei, sans-serif' font-size='48' fill='#2c4cff'>课程封面</text>
    </svg>`;
  return `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svg)}`;
})();

const resolveCover = (picPaths) => {
  if (!picPaths) return FALLBACK_COVER;
  const first = String(picPaths).split(",")[0].trim();
  if (!first) return FALLBACK_COVER;
  if (/^https?:/i.test(first)) return first;
  if (first.startsWith("/")) return `${apiBase}${first}`;
  return `${apiBase}/${first}`;
};

const parseDate = (value) => {
  if (!value) return null;
  let parsed = dayjs(value);
  if (parsed.isValid()) return parsed;

  const normalized = String(value).replace(/\//g, "-");
  parsed = dayjs(normalized);
  if (parsed.isValid()) return parsed;

  const timestamp = Date.parse(value);
  if (!Number.isNaN(timestamp)) {
    return dayjs(timestamp);
  }

  const numeric = Number(value);
  if (!Number.isNaN(numeric) && numeric > 0) {
    return dayjs(numeric);
  }

  return null;
};

const toComparableTimestamp = (value) => {
  const date = parseDate(value);
  return date ? date.valueOf() : Number.NEGATIVE_INFINITY;
};

const formatDateTime = (value) => {
  const date = parseDate(value);
  return date ? date.format("YYYY年MM月DD日 HH:mm") : "未设置";
};

const pagedCourses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return courses.value.slice(start, start + pageSize.value);
});

const totalCourses = computed(() => courses.value.length);

const sortCoursesByAddedTime = (list) => {
  return [...list].sort((a, b) => {
    const timeA = toComparableTimestamp(a?.addedTime);
    const timeB = toComparableTimestamp(b?.addedTime);
    if (timeA !== timeB) {
      return timeB - timeA;
    }
    const idA = Number(a?.id) || 0;
    const idB = Number(b?.id) || 0;
    return idB - idA;
  });
};

const loadCourses = async () => {
  try {
    if (!refreshing.value) {
      loading.value = true;
    }
    const list = await fetchCourses();
    courses.value = Array.isArray(list) ? sortCoursesByAddedTime(list) : [];
    if (currentPage.value > 1 && pagedCourses.value.length === 0) {
      currentPage.value = 1;
    }
  } catch (error) {
    ElMessage.error(error?.message || "加载课程数据失败，请稍后重试");
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

const refresh = () => {
  refreshing.value = true;
  loadCourses();
};

const handleViewCourse = (course) => {
  if (!course?.id) {
    ElMessage.warning("当前课程缺少有效的ID，无法查看详情");
    return;
  }
  router.push({ name: 'course-detail', params: { id: course.id } });
};

const handlePageChange = (page) => {
  currentPage.value = page;
  window.scrollTo({ top: 0, behavior: "smooth" });
};

onMounted(() => {
  loadCourses();
});
</script>

<template>
  <div class="home-page">
    <section class="toolbar">
      <div class="toolbar__info">
        <h1>课程总览</h1>
        <p>点击卡片即可进入课程详情，查看任务与评价内容。</p>
      </div>
      <div class="toolbar__actions">
        <el-button type="primary" size="large" @click="router.push({ name: 'course-add' })">
          发布新课程
        </el-button>
        <el-button size="large" plain :loading="refreshing" @click="refresh">
          刷新数据
        </el-button>
      </div>
    </section>

    <el-skeleton v-if="loading" :rows="6" animated class="page-skeleton" />

    <template v-else>
      <el-empty v-if="!totalCourses" description="暂无课程，请先发布课程信息" />
      <div v-else class="course-grid">
        <el-row :gutter="28">
          <el-col
            v-for="course in pagedCourses"
            :key="course.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="6"
          >
            <el-card
              class="course-card"
              shadow="hover"
              @click="handleViewCourse(course)"
              tabindex="0"
              role="button"
              @keyup.enter="handleViewCourse(course)"
            >
              <div class="course-card__cover">
                <img :src="resolveCover(course.picPaths)" :alt="course.title || '课程封面'" />
              </div>
              <div class="course-card__body">
                <h3>{{ course.title || "未命名课程" }}</h3>
                <p class="course-card__intro">{{ course.body || "暂无课程简介" }}</p>
                <el-descriptions :column="1" size="small" border>
                  <el-descriptions-item label="任课老师">{{ course.teachername || "未填写" }}</el-descriptions-item>
                  <el-descriptions-item label="课程作者">{{ course.authorName || course.realName || "未填写" }}</el-descriptions-item>
                  <el-descriptions-item label="所属类别">{{ course.categoryTitle || course.categoryname || course.categoryid || "未分类" }}</el-descriptions-item>
                  <el-descriptions-item label="开课时间">{{ formatDateTime(course.startTime) }}</el-descriptions-item>
                  <el-descriptions-item label="结课时间">{{ formatDateTime(course.endTime) }}</el-descriptions-item>
                  <el-descriptions-item label="发布时间">{{ formatDateTime(course.addedTime) }}</el-descriptions-item>
                </el-descriptions>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <div class="pagination-wrapper" v-if="totalCourses > pageSize">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalCourses"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </template>
  </div>
</template>

<style scoped>
.home-page {
  display: flex;
  flex-direction: column;
  gap: 28px;
}

.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
  background: rgba(255, 255, 255, 0.85);
  border-radius: 22px;
  padding: 28px 32px;
}

.toolbar__info h1 {
  margin: 0 0 10px;
  font-size: 30px;
  color: #1d39c4;
}

.toolbar__info p {
  margin: 0;
  color: #4a5570;
  font-size: 15px;
}

.toolbar__actions {
  display: flex;
  gap: 14px;
  flex-wrap: wrap;
}

.course-grid {
  display: flex;
  flex-direction: column;
  gap: 28px;
}

.course-card {
  border-radius: 22px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding-bottom: 12px;
  cursor: pointer;
  transition: transform 0.2s ease, background-color 0.2s ease, box-shadow 0.2s ease;
}

.course-card:hover,
.course-card:focus {
  background: #f6f8ff;
  box-shadow: 0 18px 38px rgba(64, 90, 255, 0.15);
  transform: translateY(-4px);
}

.course-card__cover {
  width: 100%;
  aspect-ratio: 16 / 9;
  border-radius: 16px;
  overflow: hidden;
  background: #f0f4ff;
}

.course-card__cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.course-card__body {
  display: flex;
  flex-direction: column;
  gap: 14px;
  margin-top: 18px;
}

.course-card__body h3 {
  margin: 0;
  font-size: 22px;
  color: #1f1f1f;
  line-height: 1.35;
}

.course-card__intro {
  margin: 0;
  color: #5e6475;
  font-size: 15px;
  line-height: 1.7;
  min-height: 48px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.el-descriptions {
  border-radius: 14px;
  overflow: hidden;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 16px 0 28px;
}

.page-skeleton {
  background: rgba(255, 255, 255, 0.6);
  border-radius: 18px;
  padding: 28px;
}

@media (max-width: 768px) {
  .toolbar__info h1 {
    font-size: 24px;
  }
  .toolbar {
    padding: 22px;
  }
  .course-card__body h3 {
    font-size: 20px;
  }
}
</style>